//
//  UPGoToApplyViewController.m
//  Uang Pasti
//
//  Created by 李永彬 on 2025/8/24.
//

#import "UPGoToApplyViewController.h"
#import "UPGoToApplyCarouselView.h"
#import "UPAuthCompletedViewController.h"
#import "UPAuthViewController.h"
#import "UPContactViewController.h"
#import "UPPersonalViewController.h"
#import "UPYINHANGViewController.h"

@interface UPGoToApplyViewController ()<UPGoToApplyCarouselViewDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIView *containerView;
@property (nonatomic, strong) UIImageView *iconImageView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *detailLabel;
@property (nonatomic, strong) UPGoToApplyCarouselView *carouselView;
@property (nonatomic, strong) UIPageControl *pageControl;
@property (nonatomic, strong) UIButton *leftButton;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) UIButton *confirmButton;
@property (nonatomic, strong) OmniosityModel *currentOmniosity;
@property (nonatomic, strong) NSString *titleName;
@property (nonatomic, strong) LoanDetailModel *currentLoanDetailModel;
@property (nonatomic, strong) NSString *vcName;

@end

@implementation UPGoToApplyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.bgImageView.image = [UIImage imageNamed:@"go_to_apply_bg"];
    self.title = LocalizableForKey(@"Product details");
    [self commonInitSubviews];
    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.scrollView.mj_header beginRefreshing];
}

- (void)fetchData {
    [SVProgressHUD show];
    NSString *pid = [NSString stringWithFormat:@"%@", self.productId];
    __block typeof(self) weakSelf = self;
    [UPStocksAPIManager fetchMyLoanDetailWithProductId:pid completion:^(LoanDetailModel * _Nullable model, NSString * _Nullable msg) {
        if (model) {
            weakSelf.currentOmniosity = model.omniosity;
            weakSelf.currentLoanDetailModel = model;
            [weakSelf.carouselView updateWithDatas:model.stultiive];
            weakSelf.pageControl.numberOfPages = model.stultiive.count;
            weakSelf.leftButton.hidden = NO;
            weakSelf.rightButton.hidden = NO;
            weakSelf.confirmButton.hidden = NO;
            [SVProgressHUD dismiss];
        } else {
            [SVProgressHUD showInfoWithStatus:msg];
        }
        [weakSelf.scrollView.mj_header endRefreshing];
    }];
}

- (void)fetchMyAddressData {
    [UPStocksAPIManager fetchAddressWithCompletion:^(ADRLapidantModel * _Nonnull model, NSString * _Nonnull msg) {
        if (model) {
            NSData *modelData = [NSKeyedArchiver archivedDataWithRootObject:model
                                                      requiringSecureCoding:YES
                                                                      error:nil];
            [UPUserDefaults setObject:modelData forKey:myAddressKey];
        }
    }];
}

- (void)commonInitSubviews {
    __weak typeof(self) weakSelf = self;
    self.scrollView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf fetchData];
        [weakSelf fetchMyAddressData];
    }];
    
    if ([self.scrollView.mj_header isKindOfClass:[MJRefreshNormalHeader class]]) {
        MJRefreshNormalHeader *header = (MJRefreshNormalHeader *)self.scrollView.mj_header;
        
        [header setTitle:@"" forState:MJRefreshStateIdle];
        [header setTitle:@"" forState:MJRefreshStatePulling];
        [header setTitle:@"" forState:MJRefreshStateRefreshing];
        header.lastUpdatedTimeLabel.hidden = YES;
        header.stateLabel.hidden = YES;
    }
    
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.top.equalTo(self.view).offset(80);
        make.bottom.equalTo(self.view).offset(-mainTabBarHeight);
    }];
    
    [self.scrollView addSubview:self.containerView];
    [self.containerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.containerView).offset(20);
        make.leading.equalTo(self.containerView).offset(20);
        make.trailing.equalTo(self.iconImageView.mas_leading).offset(-10);
    }];
    
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLabel).offset(-10);
        make.trailing.equalTo(self.containerView).offset(-16);
        make.height.mas_equalTo(119);
        make.width.mas_equalTo(122);
    }];
    
    [self.detailLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.titleLabel);
        make.top.equalTo(self.titleLabel.mas_bottom).offset(10);
    }];
    
    [self.carouselView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.containerView);
        make.top.equalTo(self.detailLabel.mas_bottom).offset(55);
        make.height.mas_equalTo(285);
        make.width.mas_equalTo(263);
    }];
    
    [self.pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.carouselView);
        make.top.equalTo(self.carouselView.mas_bottom).offset(30);
        make.height.mas_equalTo(30);
        make.leading.equalTo(self.leftButton.mas_trailing);
        make.trailing.equalTo(self.rightButton.mas_leading);
    }];
    
    [self.leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.pageControl);
        make.leading.equalTo(self.carouselView).offset(-10);
    }];
    
    [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.leftButton);
        make.trailing.equalTo(self.carouselView).offset(10);
    }];
    
    UIImage *buttonImage = [UIImage imageNamed:@"button_bg_style4"];
    CGFloat buttonHeight = 50.0;
    CGFloat buttonAspectRatio = buttonImage.size.width / buttonImage.size.height;
    CGFloat buttonWidth = buttonHeight * buttonAspectRatio;
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.rightButton.mas_bottom).offset(35);
        make.centerX.equalTo(self.containerView);
        make.height.mas_equalTo(buttonHeight);
        make.width.mas_equalTo(buttonWidth);
        make.bottom.equalTo(self.containerView);
    }];
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    self.scrollView.contentSize = self.containerView.frame.size;
}

- (UIScrollView *)scrollView {
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.directionalLockEnabled = YES;
        _scrollView.alwaysBounceVertical = YES;
        _scrollView.alwaysBounceHorizontal = NO;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.userInteractionEnabled = YES;
    }
    return _scrollView;
}

- (UIView *)containerView {
    if (!_containerView) {
        _containerView = [[UIView alloc] init];;
    }
    return _containerView;
}

- (UIImageView *)iconImageView {
    if (!_iconImageView) {
        _iconImageView = [[UIImageView alloc] init];
        _iconImageView.contentMode = UIViewContentModeScaleAspectFit;
        _iconImageView.image = [UIImage imageNamed:@"auth_top_icon"];
        [self.containerView addSubview:_iconImageView];
    }
    return _iconImageView;
}

- (UILabel *)titleLabel {
    if (!_titleLabel) {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.font = [UIFont boldSystemFontOfSize:14];
        _titleLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        _titleLabel.textAlignment = NSTextAlignmentLeft;
        _titleLabel.numberOfLines = 0;
        _titleLabel.text = LocalizableForKey(@"loan issuance in as fast as one minute");
        [self.containerView addSubview:_titleLabel];
    }
    return _titleLabel;
}

- (UILabel *)detailLabel {
    if (!_detailLabel) {
        _detailLabel = [[UILabel alloc] init];
        _detailLabel.font = [UIFont systemFontOfSize:13];
        _detailLabel.textColor = [UIColor colorWithHexString:@"#000000"];
        _detailLabel.textAlignment = NSTextAlignmentLeft;
        _detailLabel.numberOfLines = 0;
        _detailLabel.text = LocalizableForKey(@"Complete the certifcation and start your loan journey");
        [self.containerView addSubview:_detailLabel];
    }
    return _detailLabel;
}

- (UPGoToApplyCarouselView *)carouselView {
    if (!_carouselView) {
        _carouselView = [[UPGoToApplyCarouselView alloc] init];
        _carouselView.delegate = self;
        [self.containerView addSubview:_carouselView];
    }
    return _carouselView;
}

- (UIPageControl *)pageControl {
    if (!_pageControl) {
        _pageControl= [[UIPageControl alloc] init];
        _pageControl.currentPageIndicatorTintColor = [UIColor colorWithHexString:@"#F9D14B"];
        _pageControl.pageIndicatorTintColor = [[UIColor colorWithHexString:@"#000000"] colorWithAlphaComponent:0.66];
        _pageControl.userInteractionEnabled = NO;
        [self.containerView addSubview:self.pageControl];
    }
    return _pageControl;
}

- (UIButton *)leftButton {
    if (!_leftButton) {
        _leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_leftButton setImage:[UIImage imageNamed:@"go_to_apply_left_btn"] forState:UIControlStateNormal];
        [_leftButton addTarget:self action:@selector(clickLeftButtonAction) forControlEvents:UIControlEventTouchUpInside];
        _leftButton.hidden = YES;
        [self.containerView addSubview:_leftButton];
    }
    return _leftButton;
}

- (UIButton *)rightButton {
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_rightButton setImage:[UIImage imageNamed:@"go_to_apply_right_btn"] forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(clickRightButtonAction) forControlEvents:UIControlEventTouchUpInside];
        _rightButton.hidden = YES;
        [self.containerView addSubview:_rightButton];
    }
    return _rightButton;
}

- (void)clickLeftButtonAction {
    NSInteger currentPage = self.pageControl.currentPage;
    NSInteger toPage = currentPage - 1;
    if (currentPage - 1 < 0) {
        toPage = self.carouselView.dataSources.count - 1;
    }
    [self.carouselView scrollToIndex:toPage];
}

- (void)clickRightButtonAction {
    NSInteger currentPage = self.pageControl.currentPage;
    NSInteger toPage = currentPage + 1;
    if (currentPage + 1 >= self.carouselView.dataSources.count) {
        toPage = 0;
    }
    [self.carouselView scrollToIndex:toPage];
}

- (UIButton *)confirmButton {
    if (!_confirmButton) {
        _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmButton setBackgroundImage:[UIImage imageNamed:@"button_bg_style4"] forState: UIControlStateNormal];
        [_confirmButton setTitle:LocalizableForKey(@"Confirm") forState:UIControlStateNormal];
        [_confirmButton setTitleColor:[UIColor colorWithHexString:@"#000000"] forState:UIControlStateNormal];
        [_confirmButton addTarget:self action:@selector(clickConfirmBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.hidden = YES;
        [self.containerView addSubview:_confirmButton];
    }
    return _confirmButton;
}

#pragma mark - Method
- (void)clickConfirmBtnAction {
    [self handleConfirmAction];
}

- (void)pushToAuthVC {
    UPAuthViewController *authVC = [[UPAuthViewController alloc] init];
    authVC.currentOmniosity = self.currentOmniosity;
    authVC.titleName = self.titleName;
    authVC.currentLoanDetailModel = self.currentLoanDetailModel;
    authVC.vcName = self.vcName;
    [self.navigationController pushViewController:authVC animated:YES];
}

- (void)pushToAuthCompletedVC {
    UPAuthCompletedViewController *completedVC = [[UPAuthCompletedViewController alloc] init];
    completedVC.currentOmniosity = self.currentOmniosity;
    completedVC.titleName = self.titleName;
    completedVC.currentLoanDetailModel = self.currentLoanDetailModel;
    completedVC.vcName = self.vcName;
    [self.navigationController pushViewController:completedVC animated:YES];
}

- (void)pushToPersonalVC {
    UPPersonalViewController *vc = [[UPPersonalViewController alloc] init];
    vc.currentOmniosity = self.currentOmniosity;
    vc.titleName = self.titleName;
    vc.currentLoanDetailModel = self.currentLoanDetailModel;
    vc.vcName = self.vcName;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pushToContactVC {
    UPContactViewController *vc = [[UPContactViewController alloc] init];
    vc.currentOmniosity = self.currentOmniosity;
    vc.titleName = self.titleName;
    vc.currentLoanDetailModel = self.currentLoanDetailModel;
    vc.vcName = self.vcName;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)pushToBankVC {
    UPYINHANGViewController *vc = [[UPYINHANGViewController alloc] init];
    vc.currentOmniosity = self.currentOmniosity;
    vc.titleName = self.titleName;
    vc.currentLoanDetailModel = self.currentLoanDetailModel;
    vc.vcName = self.vcName;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)handleConfirmAction {
    if (self.currentLoanDetailModel.miasmaistic == nil) {
        NSDictionary *dic = @{
            @"followUpData": self.currentOmniosity
        };
        [[NSNotificationCenter defaultCenter] postNotificationName:kFollowUpMyOrderKey
                                                            object:nil
                                                          userInfo:dic];
    }
 
    if (self.currentLoanDetailModel.miasmaistic.saccular == nil) {
        return;
    }
    
    self.titleName = self.currentLoanDetailModel.miasmaistic.musetic;
    
    [self pushToVC:self.currentLoanDetailModel.miasmaistic.saccular completed:NO];
}

- (void)pushToVC: (NSString *)vcName completed: (BOOL)isCompleted {
    self.vcName = vcName;
    if ([vcName isEqualToString:@"noct"]) {
        if (isCompleted) {
            [self pushToAuthCompletedVC];
        } else {
            [self pushToAuthVC];
        }
    } else if ([vcName isEqualToString:@"athroidlike"]) {
        [self pushToPersonalVC];
    } else if ([vcName isEqualToString:@"acerbitude"]) {
        [self pushToContactVC];
    } else if ([vcName isEqualToString:@"per"]) {
        [self pushToBankVC];
    }
}

#pragma mark -UPGoToApplyCarouselViewDelegate
- (void)carouselView:(UPGoToApplyCarouselView *)carouselView didSelectItemAtIndex:(NSInteger)index data:(StultiiveModel *)data {
    self.titleName = data.musetic;
    if ([data.septuagentic boolValue]) {
        [self pushToVC:data.saccular completed:YES];
    } else {
        [self handleConfirmAction];
    }
}

- (void)carouselView:(UPGoToApplyCarouselView *)carouselView didScrollToIndex:(NSInteger)index data:(StultiiveModel *)data {
    
    self.pageControl.currentPage = index;
}

@end
